var currentPage = 1;

$(document).ready(function()
{
    loadGallery(currentPage);

    $(document).on('click', '#gallery-nav-right a', function(e){
        e.preventDefault();
        currentPage++;
        loadGallery(currentPage);

    });

    $(document).on('click', '#gallery-nav-left a', function(e){
        e.preventDefault();
        if (currentPage > 0)
            currentPage--;
        loadGallery(currentPage);
    });

});

function loadGallery(page) {
    $("#gallery").load(BASEURL+'ajax/loadimg?page='+page, function(){
        var n=1;
        $("#gallery img.item-thumb").after('<img src="'+BASEURL+'assets/img/ajax-loader.gif" />')
            .hide();
        $("#gallery img.item-thumb")
            .sort(function() {return 0.5 - Math.random()})
            .one('load', function() {
            $(this).delay(n*150).fadeIn(400);
            $(this).delay(n*150).parent("a").attr('href', $(this).parent("a").attr('data-href')).fancybox();
            n++;
        }).each(function() {
                if(this.complete) $(this).load();
            });
    });
}
